package com.orcamento.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.jdbc.core.JdbcTemplate;

public class AppConfig {
	
	private static JdbcTemplate jdbcTemplate;
	private static Properties properties;
	
	private static String getValue(String key) {
		return (String) jdbcTemplate.queryForObject("SELECT STVALOR FROM appconfig WHERE STCHAVE = ?", new Object[] { key }, String.class);
	}
	
	public static String getProperty(String key) {
		if( key == null || key.equals("")  ) {
			return null;
		}
		return properties.getProperty(key);
	}
	
	public static String getUrlApplication() {
		return getValue("url.application");
	}
	
	public static String getImagesStaticsUrl() {
		return getValue("url.statics.img");
	}
	
	public static String getJavascriptStaticsUrl() {
		return getValue("url.statics.js");
	}
	
	public static String getCssStaticsUrl() {
		return getValue("url.statics.css");
	}
	
	public static String getEnv() {
		return getProperty("env");
	}

	public static Integer[] getYears() {
		Integer startYear = Integer.valueOf( getValue("report.start.year") );
		List<Integer> years = new ArrayList<Integer>();
		for(int i = CalendarUtil.getCurrentYear(); i >= startYear; i--) {
			years.add( i );
		}
		Collections.sort(years);
		return years.toArray( new Integer[years.size()] );
	}
	
	public static Integer getStartMonth() {
		return Integer.valueOf( getValue("report.start.month") );
	}
	
	public static Long getCreditCardEventId() {
		return Long.valueOf( getValue("event.creditCard.id") );
	}

	public static DateTime getStartDate() {
		return CalendarUtil.toDate(1, getStartMonth(), getYears()[0]);
	}
	
	public static String getDomainCookie() {
		return getValue("cookie.authentication.domain");
	}
	
	public static String getAccountCookieName() {
		return getValue("cookie.authentication.name");
	}
	
	public static String getDownloadPath() {
		return getValue("download.path");
	}
	
	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		AppConfig.jdbcTemplate = jdbcTemplate;
	}
	
	@Autowired
	public void setProperties(Properties properties) throws Exception {
		ClassPathResource resource = new ClassPathResource("locale/lang_pt_BR.properties");
		AppConfig.properties = PropertiesLoaderUtils.loadProperties(resource);
	}

}
